package com.galeno.huancun;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author galeno
 * @Title:
 * @Description:
 * @date 2021/7/3022:48
 */
public class MapSideJoin {
    static class MapSideJoinMapper extends Mapper<LongWritable, Text,Text, NullWritable>{
        //获取所有用户信息
        Map<String,String> user=null;

        @Override
        protected void setup(Context context) throws IOException, InterruptedException {
            user=new HashMap<>();
            //读取分布式缓存在本地的一个本地文件,位置在该项目的类路径下
            BufferedReader br=new BufferedReader(new FileReader("user.txt"));
            String line=null;
            while ((line= br.readLine())!=null){
                String uid = line.split(",")[0];
                user.put(uid,line);

            }




        }
        Text k=new Text();

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String[] split = line.split("\\s+");
            String oid = split[0];
            String uid = split[1];
            String user = this.user.getOrDefault(uid, "空");
            String result=oid+" ,"+user;
            k.set(result);
            context.write(k,NullWritable.get());

        }
    }

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException, URISyntaxException {
        // 创建一个配置对象
        Configuration conf = new Configuration();
        // 1 设置运行模式为 yarn
        conf.set("mapreduce.framework.name", "yarn");
        // 初始化一个Job
        Job job = Job.getInstance(conf, "join");
        // 5 打包 指定jar包的位置
        job.setJarByClass(MapSideJoin.class);
        // 设置map类
        job.setMapperClass(MapSideJoinMapper.class);
        // 设置Reducer类

        // 设置map和Reducer类的输出类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(NullWritable.class);
        // 设置分布式缓存文件
        job.addCacheFile(new URI("hdfs://galeno01:8020/user.txt"));
        //数据的输入路径
        FileInputFormat.setInputPaths(job,new Path("/orders"));
        // 输出的结果保存路径
        FileOutputFormat.setOutputPath(job,new Path("/join_res"));
        // 运行Job  等待运行完毕
        job.waitForCompletion(true) ;
        job.waitForCompletion(true) ;
    }



}
